<template>
  <div class="pl20" v-for="item in folder" :key="item.id">
    <span class="checkbox" :class="item.checked" @click="handleClick(item, item.checked)"></span>
    {{ item.name }}
    <tree v-if="item.children" :folder="item.children"></tree>
  </div>
</template>

<script setup>
defineProps({
  folder: Array
})

function handleClick(item, val) {
  if (!val || val === 'half') {
    item.checked = 'all'
    checkLater(item, 'all')
  } else if (val === 'all') {
    item.checked = ''
    checkLater(item, '')
  }
  let parent = item.parent
  while (parent) {
    checkParent(parent)
    parent = parent.parent
  }
}
function checkLater(item, flag) {
  if (item.children) {
    item.children.forEach(cItem => {
      cItem.checked = flag
      checkLater(cItem, flag)
    })
  }
}
function checkParent(item) {
  if (item.children) {
    const all = item.children.every(cItem => cItem.checked === 'all')
    const none = item.children.every(cItem => cItem.checked === '')
    if (all) {
      item.checked = 'all'
    } else if (none) {
      item.checked = ''
    } else {
      item.checked = 'half'
    }
  }
}
</script>

<style scoped lang="less">
.checkbox {
  display: inline-block;
  width: 12px;
  height: 12px;
  border: 1px solid #999;
  margin-right: 4px;
  cursor: pointer;
}
.all {
  background-color: rgba(0, 0, 0, 1);
}
.half {
  background-color: rgba(0, 0, 0, 0.5);
}
.pl20 {
  padding-left: 20px;
}
</style>
